<?php

declare(strict_types=1);

namespace App\Service;
/**
 * 申请入驻服务
 * Class FlyShopApplyService
 * @package App\Service
 */
class FlyShopApplyService extends BaseService
{

    const STATUS_DRAFT = 0;
    const STATUS_WAIT_CHECK = 1;
    const STATUS_CHECKED = 2;
    const STATUS_REFUSE = 3;

    /**
     * 创建申请单
     * @param array $params
     * @param bool $return_id
     * @return int
     */
    public function createApplyOrder(array $params, bool $return_id = true): int
    {
        $apply_order_data = [
            'shop_id' => $params['shop_id'],
            'user_id' => $params['user_id'],
            'apply_time' => time(),
            'apply_type' => $params['type'],
            'status' => (in_array($params['apply_order_type'], [3, 4, 5])) ? 1 : 0, //申请状态：草稿 完善信息后变为待审核 (修改信息直接提交待审核)
            'apply_order_type' => $params['apply_order_type']
        ];
        $model = $this->getModelInstance();
        foreach ($apply_order_data as $f => $v) {
            $model->$f = $v;
        }
        if (!$model->save()) {
            return 0;
        }
        return $return_id ? $model->id : 0;
    }

    /**
     * 更新申请单
     * @param array $params
     * @param int $apply_id
     * @return bool
     */
    public function saveApplyOrder(array $params, int $apply_id): bool
    {

        $model = $this->getModelInstance()->find($apply_id);
        $save_fields = ['status', 'apply_time'];
        foreach ($params as $f => $param) {
            if (in_array($f, $save_fields)) {
                $model->$f = $param;
            }
        }

        if (!$model->save()) {
            return false;
        }
        return true;
    }

    /**
     * 获取入驻申请单状态：0已申请待完善 1已提交待审核 2已审核通过 4驳回或未申请
     * @param int $user_id
     * @param int $style_type
     * @return array
     */
    public function getApplyNow(int $user_id, int $style_type): array
    {
        // 最新申请单状态
        $status = $this->getInstance()
            ->with(['apply_info'])
            ->where(['user_id' => $user_id, 'shop_style' => $style_type])
            ->orderBy('status', 'asc')// 0草稿 1待审核 2审核通过 3被驳回
            ->orderBy('apply_time', 'desc')
            ->first();
        return empty($status) ? [] : $status->toArray();
    }

    /**
     * 获取当前模型实例
     * @return mixed
     */
    public function getInstance()
    {
        return $this->getModelInstance();
    }

}